import os
import shutil
import unittest
import fdeImport
import uuid
import json

from shapely.wkt import loads


# Test geometry

class TestImport(unittest.TestCase):
    def setUp(self):
        self.host = "http://localhost:8001"
        self.dataSetName = "testImport"
        self.pgConn = {"type": 5, "database": "sdb", "host": "10.5.69.22", "port": 15431, "user": "root",
                       "password": "Gld@123"}

    def copyData(self, path, name):
        random_uuid = uuid.uuid4().hex

        shp_lst = ['%s.shp' % name, '%s.dbf' % name, '%s.prj' % name, '%s.shx' % name]
        for f in shp_lst:
            src = os.path.join(path, f)
            dest = os.path.join(path, random_uuid, f)
            if os.path.exists(src):
                os.makedirs(os.path.dirname(dest), exist_ok=True)
                shutil.copy2(src, dest)
        return os.path.join(path, random_uuid)

    def assert_4490(self, geometry):
        self.assertTrue(geometry)
        g = loads(geometry)
        l, b, r, t = g.bounds
        self.assertTrue(-180.0 <= l <= 180.0 and -180.0 <= r <= 180.0 and -90.0 <= t <= 90.0 and -90.0 <= b <= 90.0)

    def assert_3857(self, geometry):
        self.assertTrue(geometry)
        g = loads(geometry)
        l, b, r, t = g.bounds
        self.assertTrue(l > 180.0 and r > 180.0 and t > 90.0 and b > 90.0)

    def assert_import(self, uuid_path):
        fdeImport.createDatasetIfNotExists(self.host, self.pgConn, self.dataSetName)

        ret = fdeImport.testImportVectorWithAttachment(self.host, uuid_path, self.pgConn, self.dataSetName)
        for resp in ret:
            resp_j = json.loads(resp.text)
            self.assertEqual(resp_j['code'], 'success')
            self.assertEqual(resp_j['data']['status'], 1)
            for fc in resp_j['data']['featureClassResultInfos']:
                self.assertTrue(len(fc['featureCounts']) > 0)
                for cnt in fc['featureCounts']:
                    self.assertTrue(cnt > 0)

            fcName = resp_j['data']['featureClassName']
            data = fdeImport.queryFeatureClass(self.host, self.pgConn, self.dataSetName, fcName)
            self.assertTrue(len(data) > 0)
            geo = data[0]['geometry']
            geo_3857 = data[0]['geometry_3857']
            self.assert_4490(geo)
            self.assert_3857(geo_3857)

    # @unittest.skip("This test")
    def test_import_success(self):
        url = "https://cimcube-test.glodon.com/resource/adcode/adcode.zip"

        path = fdeImport.get_current_path()
        fdeImport.download([url], path)
        zip_file = os.path.join(path, "adcode.zip")
        self.assertTrue(os.path.exists(zip_file))

        fdeImport.unzip(zip_file, path)

        uuid_path = self.copyData(path, 'province')
        self.assert_import(uuid_path)
        shutil.rmtree(uuid_path)

    def test_import_coords(self):
        name = '政府机关'

        url_lst = ["https://cimcube-test.glodon.com/resource/FDEStore/test/20250120/%s.shp" % name,
                   "https://cimcube-test.glodon.com/resource/FDEStore/test/20250120/%s.dbf" % name,
                   "https://cimcube-test.glodon.com/resource/FDEStore/test/20250120/%s.prj" % name,
                   "https://cimcube-test.glodon.com/resource/FDEStore/test/20250120/%s.shx" % name
                   ]

        path = fdeImport.get_current_path()
        fdeImport.download(url_lst, path)

        shp_file = os.path.join(path, "%s.shp" % name)
        self.assertTrue(os.path.exists(shp_file))

        uuid_path = self.copyData(path, name)
        self.assert_import(uuid_path)
        shutil.rmtree(uuid_path)


if __name__ == "__main__":
    unittest.main()
